package ae.pcfc.cldos.online.common.manager.provider;

import java.io.File;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.validator.GenericValidator;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import ae.pcfc.cldos.online.common.exception.SytemException;
import ae.pcfc.cldos.online.common.manager.MailManager;

public class MailManagerImpl implements MailManager {
	private JavaMailSender mailSender;
	private SimpleMailMessage templateMessage;

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setTemplateMessage(SimpleMailMessage templateMessage) {
		this.templateMessage = templateMessage;
	}

	public void sendMail(String toAddr, String subject, String body,
			List<File> attachPathList) throws SytemException {

		MimeMessageHelper helper = null;
		MimeMessage message = mailSender.createMimeMessage();

		try {
			if (attachPathList != null && attachPathList.size() != 0) {

				helper = new MimeMessageHelper(message, true, "UTF-8");
			} else {
				helper = new MimeMessageHelper(message, false, "UTF-8");
			}

			helper.setValidateAddresses(true);
			helper.setFrom(templateMessage.getFrom());
			if (!GenericValidator.isBlankOrNull(toAddr)) {
				helper.setTo(toAddr);
			} else {
				helper.setTo(templateMessage.getTo());
			}
			if (!GenericValidator.isBlankOrNull(subject)) {
				helper.setSubject(subject);
			} else {
				helper.setSubject(templateMessage.getSubject());
			}
			if (!GenericValidator.isBlankOrNull(body)) {
				helper.setText(body);
			} else {
				helper.setText(templateMessage.getText());
			}
			if (attachPathList != null && attachPathList.size() != 0) {
				for (File file : attachPathList) {
					helper.addAttachment(file.getName(), file);
				}

			}

			mailSender.send(message);
		} catch (MailException ex) {
			throw new SytemException(ex);
		} catch (MessagingException e) {
			throw new SytemException(e);
		}

	}

}
